import java.util.LinkedList;
import java.util.Queue;

public class Star implements Stream {
    private Stream stm;
    private boolean firstBatch = true;
    private HistoryStream historyStream = new HistoryStream();
    private Queue<String> tor = new LinkedList<String>();

    public Star(Stream stm) {
        this.stm = stm;
    }

    public String next() {
        String res;
        if (historyStream.size() == 0) {
            historyStream.add("");
            res = "";
        } else {
            res = historyStream.next();
            if (res == null) {
                res = getFromStream();
            }
        }
        return res;
    }

    private String getFromStream() {
        String res = stm.next();
        if (res == null) {
            firstBatch = false;
            stm.reset();
            res = stm.next();
        }
        if (!firstBatch) {
            String polled = tor.poll();
            if (polled != null) {
                res += polled;
            }
        }
        if (res != null) {
            tor.add(res);
            historyStream.add(res);
        }
        return res;
    }

    public String prev() {
        return historyStream.prev();
    }

    public void reset() {
        firstBatch = true;
        historyStream.reset();
        tor.clear();
        stm.reset();
    }
}
